<template>
  <div class="text-description">
    <el-row :gutter="20" class="description-content">
      <!-- 左侧概览信息 -->
      <el-col :span="8">
        <div class="route-overview">
          <h3 class="overview-title">
            {{ props.travelMode === "transit" ? "可选乘车方案" : "路线概览" }}
          </h3>
          <template v-if="processedRouteData">
            <!-- 公交方案选择器 -->
            <div
              v-if="travelMode === 'transit' && allTransitRoutes?.length > 1"
              class="route-selector"
            >
              <div class="preview-list">
                <div class="preview-items">
                  <div
                    v-for="(route, index) in allTransitRoutes"
                    :key="index"
                    class="preview-item"
                    :class="{ active: selectedRouteIndex === index }"
                    @click="selectedRouteIndex = index"
                  >
                    <div class="item-header">
                      <span class="item-title">方案 {{ index + 1 }}</span>
                      <el-tag size="small" type="primary" effect="plain" v-if="index === 0"
                        >推荐</el-tag
                      >
                    </div>
                    <div class="item-info">
                      <span class="info-item">
                        <el-icon><Timer /></el-icon>
                        {{ formatDuration(route.duration) }}
                      </span>
                      <span class="info-item">
                        <el-icon><Location /></el-icon>
                        {{ formatDistance(route.distance) }}
                      </span>
                      <span class="info-item">
                        <el-icon><Money /></el-icon>
                        ¥{{ route.price || 0 }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 非公交线路的概览信息 -->
            <div class="overview-items" v-if="travelMode !== 'transit'">
              <div class="overview-item">
                <el-icon><Timer /></el-icon>
                <div class="item-content">
                  <div class="item-label">预计用时</div>
                  <div class="item-value">{{ formatDuration(processedRouteData.duration) }}</div>
                </div>
              </div>
              <div class="overview-item">
                <el-icon><Location /></el-icon>
                <div class="item-content">
                  <div class="item-label">总距离</div>
                  <div class="item-value">{{ formatDistance(processedRouteData.distance) }}</div>
                </div>
              </div>
              <div
                class="overview-item"
                v-if="travelMode === 'driving' && processedRouteData.price !== undefined"
              >
                <el-icon><Money /></el-icon>
                <div class="item-content">
                  <div class="item-label">票价</div>
                  <div class="item-value">¥{{ processedRouteData.price }}</div>
                </div>
              </div>
              <div class="overview-item" v-if="travelMode === 'driving'">
                <el-icon><Money /></el-icon>
                <div class="item-content">
                  <div class="item-label">预计花费</div>
                  <div class="item-value">¥{{ calculateCost(processedRouteData.distance) }}</div>
                </div>
              </div>
            </div>
            <div class="traffic-legend" v-if="travelMode === 'driving'">
              <h4>路况说明</h4>
              <div class="legend-items">
                <div class="legend-item">
                  <span class="dot traffic-smooth"></span>
                  <span>畅通</span>
                </div>
                <div class="legend-item">
                  <span class="dot traffic-slow"></span>
                  <span>缓行</span>
                </div>
                <div class="legend-item">
                  <span class="dot traffic-congested"></span>
                  <span>拥堵</span>
                </div>
                <div class="legend-item">
                  <span class="dot traffic-heavily-congested"></span>
                  <span>严重拥堵</span>
                </div>
              </div>
            </div>
          </template>
          <el-empty v-else description="暂无路线数据" />
        </div>
      </el-col>

      <!-- 右侧详细路线 -->
      <el-col :span="16">
        <div class="route-details">
          <h3 class="details-title">详细路线</h3>
          <div class="route-steps" v-if="processedRouteData">
            <el-timeline>
              <el-timeline-item
                center
                v-for="(step, index) in processedRouteData.steps"
                :key="index"
                :color="getStepColor(step)"
                hide-timestamp
              >
                <div class="step-content">
                  <div v-html="step.instruction"></div>
                  <div class="step-info">
                    <span>预计通行距离：{{ formatDistance(step.distance) }}</span>
                    <span>预计通行时间：{{ formatDuration(step.duration) }}</span>
                    <span
                      v-if="
                        (travelMode === 'driving' || travelMode === 'riding') &&
                        step.traffic_condition?.[0]
                      "
                      :class="['traffic-tag', getTrafficClass(step.traffic_condition[0].status)]"
                    >
                      {{ getTrafficStatus(step.traffic_condition[0].status) }}
                    </span>
                  </div>

                  <!-- 公交车信息 -->
                  <div v-if="step.type === 3 && step.vehicle" class="transit-info">
                    <el-descriptions :column="2" border>
                      <el-descriptions-item>
                        <template #label>
                          <div class="label-with-icon">
                            <el-icon><Van /></el-icon>
                            <span>线路</span>
                          </div>
                        </template>
                        <div class="desc-item-content">
                          <el-tag
                            :style="{ backgroundColor: step.vehicle.line_color, color: '#fff' }"
                          >
                            {{ step.vehicle.name }}
                          </el-tag>
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template #label>
                          <div class="label-with-icon">
                            <el-icon><TurnOff /></el-icon>
                            <span>方向</span>
                          </div>
                        </template>
                        <div class="desc-item-content">
                          <span>{{ step.vehicle.direct_text }}</span>
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template #label>
                          <div class="label-with-icon">
                            <el-icon><Clock /></el-icon>
                            <span>首班</span>
                          </div>
                        </template>
                        <div class="desc-item-content">
                          <span>{{ step.vehicle.start_time }}</span>
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template #label>
                          <div class="label-with-icon">
                            <el-icon><Clock /></el-icon>
                            <span>末班</span>
                          </div>
                        </template>
                        <div class="desc-item-content">
                          <span>{{ step.vehicle.end_time }}</span>
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template #label>
                          <div class="label-with-icon">
                            <el-icon><Position /></el-icon>
                            <span>上车站</span>
                          </div>
                        </template>
                        <div class="desc-item-content">
                          <span>{{ step.vehicle.start_name }}</span>
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template #label>
                          <div class="label-with-icon">
                            <el-icon><Flag /></el-icon>
                            <span>下车站</span>
                          </div>
                        </template>
                        <div class="desc-item-content">
                          <span>{{ step.vehicle.end_name }}</span>
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template #label>
                          <div class="label-with-icon">
                            <el-icon><Odometer /></el-icon>
                            <span>经过站数</span>
                          </div>
                        </template>
                        <div class="desc-item-content">
                          <span>{{ step.vehicle.stop_num }}站</span>
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item v-if="step.vehicle.total_price !== undefined">
                        <template #label>
                          <div class="label-with-icon">
                            <el-icon><Money /></el-icon>
                            <span>票价</span>
                          </div>
                        </template>
                        <div class="desc-item-content">
                          <span>¥{{ step.vehicle.total_price }}</span>
                        </div>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
          <el-empty v-else description="暂无路线数据" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import {
  Timer,
  Location,
  Money,
  Van,
  TurnOff,
  Clock,
  Position,
  Flag,
  Odometer,
} from "@element-plus/icons-vue";
import { computed, ref } from "vue";

type Vehicle = {
  direct_text: string;
  end_name: string;
  end_time: string;
  line_color: string;
  name: string;
  start_name: string;
  start_time: string;
  stop_num: number;
  total_price: number;
};

type Step = {
  distance: number;
  duration: number;
  instruction: string;
  path: string;
  type?: number;
  vehicle?: Vehicle;
  traffic_condition?: Array<{
    status: number;
    geo_cnt: number;
  }>;
};

type Props = {
  routeData: any;
  travelMode: string;
};

const props = defineProps<Props>();
const selectedRouteIndex = ref(0);

// 所有公交路线方案
const allTransitRoutes = computed(() => {
  if (props.travelMode === "transit" && props.routeData?.routes) {
    return props.routeData.routes;
  }
  return null;
});

// 计算属性：处理路线数据
const processedRouteData = computed(() => {
  if (!props.routeData) return null;

  // 如果是公交路线，返回选中的方案
  if (props.travelMode === "transit") {
    if (props.routeData.routes && props.routeData.routes.length > 0) {
      return props.routeData.routes[selectedRouteIndex.value];
    }
    return null;
  }

  // 其他出行方式，保持原有格式
  return {
    ...props.routeData,
    steps: props.routeData.steps.map((step: any) => ({
      ...step,
      type: props.travelMode === "driving" ? 1 : 5,
    })),
  };
});

// 格式化距离
const formatDistance = (meters: number) => {
  return meters >= 1000 ? `${(meters / 1000).toFixed(1)}公里` : `${meters}米`;
};

// 格式化时间
const formatDuration = (seconds: number) => {
  if (!seconds || seconds < 0) return "0秒";

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;

  let result = "";
  if (hours > 0) {
    result += `${hours}小时`;
  }
  if (minutes > 0) {
    result += `${minutes}分`;
  }
  if (remainingSeconds > 0 || (!hours && !minutes)) {
    result += `${remainingSeconds}秒`;
  }
  return result;
};

// 计算行驶成本
const calculateCost = (distance: number) => {
  const fuelCost = (distance / 1000) * (8 / 100) * 7;
  const totalCost = fuelCost + (distance > 100000 ? 50 : 0);
  return totalCost.toFixed(1);
};

// 获取交通状况描述
const getTrafficStatus = (status: number) => {
  const statusMap = {
    0: "畅通",
    1: "缓行",
    2: "拥堵",
    3: "严重拥堵",
  };
  return statusMap[status as keyof typeof statusMap] || "未知";
};

// 获取交通状况样式类
const getTrafficClass = (status: number) => {
  const classMap = {
    0: "traffic-smooth",
    1: "traffic-slow",
    2: "traffic-congested",
    3: "traffic-heavily-congested",
  };
  return classMap[status as keyof typeof classMap] || "";
};

// 获取步骤颜色
const getStepColor = (step: Step) => {
  if (step.type === 3) {
    return step.vehicle?.line_color || "#409EFF"; // 使用公交线路的颜色
  }

  if (step.type === 5) {
    return "#67C23A"; // 步行路段使用绿色
  }

  if (step.type === 1) {
    if (!step.traffic_condition?.[0]) return "#409EFF";

    const status = step.traffic_condition[0].status;
    switch (status) {
      case 0:
        return "#67C23A"; // 畅通
      case 1:
        return "#E6A23C"; // 缓行
      case 2:
        return "#F56C6C"; // 拥堵
      case 3:
        return "#909399"; // 严重拥堵
      default:
        return "#409EFF";
    }
  }

  return "#409EFF";
};
</script>

<style lang="scss" scoped>
.text-description {
  height: 100%;
  background-color: #fff;

  .description-content {
    height: 100%;

    .route-overview,
    .route-details {
      height: 100%;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 8px;
    }

    .overview-title,
    .details-title {
      margin-bottom: 20px;
      color: #303133;
      font-size: 18px;
      font-weight: 600;
    }

    .overview-items {
      .overview-item {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        padding: 15px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

        .el-icon {
          font-size: 24px;
          color: #409eff;
          margin-right: 15px;
        }

        .item-content {
          .item-label {
            color: #909399;
            font-size: 14px;
            margin-bottom: 4px;
          }

          .item-value {
            color: #303133;
            font-size: 16px;
            font-weight: 500;
          }
        }
      }
    }

    .traffic-legend {
      margin-top: 30px;
      padding: 15px;
      background-color: #fff;
      border-radius: 8px;

      h4 {
        margin: 0 0 15px 0;
        color: #606266;
        font-size: 14px;
      }

      .legend-items {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;

        .legend-item {
          display: flex;
          align-items: center;
          font-size: 13px;
          color: #606266;

          .dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 6px;

            &.traffic-smooth {
              background-color: #67c23a;
            }

            &.traffic-slow {
              background-color: #e6a23c;
            }

            &.traffic-congested {
              background-color: #f56c6c;
            }

            &.traffic-heavily-congested {
              background-color: #909399;
            }
          }
        }
      }
    }

    .route-details {
      .route-steps {
        height: calc(100vh - 280px);
        overflow-y: auto;
        padding-right: 10px;

        .step-content {
          font-size: 13px;

          :deep(b) {
            color: #409eff;
            font-weight: bold;
          }

          .step-info {
            margin-top: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #909399;
            font-size: 12px;

            .traffic-tag {
              padding: 2px 6px;
              border-radius: 4px;

              &.traffic-smooth {
                background-color: #f0f9eb;
                color: #67c23a;
              }

              &.traffic-slow {
                background-color: #fdf6ec;
                color: #e6a23c;
              }

              &.traffic-congested {
                background-color: #fef0f0;
                color: #f56c6c;
              }

              &.traffic-heavily-congested {
                background-color: #f4f4f5;
                color: #909399;
              }
            }
          }
        }
      }
    }

    .transit-info {
      padding: 12px;

      :deep(.el-descriptions) {
        margin-top: 8px;

        .el-descriptions__cell {
          padding: 8px 12px;
          background-color: #ffffff;
        }

        .desc-item-content {
          display: flex;
          align-items: center;
          gap: 8px;

          .el-icon {
            font-size: 16px;
            color: #909399;
          }

          span {
            color: #303133;
          }
        }

        .label-with-icon {
          display: flex;
          align-items: center;
          gap: 4px;

          .el-icon {
            font-size: 14px;
            color: #909399;
          }

          span {
            color: #606266;
          }
        }
      }
    }

    .route-selector {
      margin-bottom: 20px;

      .preview-list {
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

        .preview-title {
          padding: 12px 16px;
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          border-bottom: 1px solid #ebeef5;
        }

        .preview-items {
          padding: 8px;
        }

        .preview-item {
          padding: 12px;
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            background-color: #f5f7fa;
          }

          &.active {
            background-color: #ecf5ff;
            border: 1px solid #409eff;

            .item-title {
              color: #409eff;
            }
          }

          & + .preview-item {
            margin-top: 8px;
          }

          .item-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 8px;

            .item-title {
              font-weight: 500;
            }
          }

          .item-info {
            display: flex;
            gap: 16px;
            color: #909399;
            font-size: 13px;

            .info-item {
              display: flex;
              align-items: center;
              gap: 4px;

              .el-icon {
                font-size: 14px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
